package seqlist.stack_queue.leetcode;

import java.util.Stack;

/**
 * @author yuisama
 * @date 2023/03/21 20:47
 * 有效的括号
 **/
public class Num20_ValidString {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                // 碰到左括号直接入栈
                stack.push(c);
            }else {
                // 此时c为右括号
                if (stack.isEmpty()) {
                    // 找到反例
                    return false;
                }
                char top = stack.pop();
                if (c == ')' && top != '(') {
                    return false;
                }
                if (c == ']' && top != '[') {
                    return false;
                }
                if (c == '}' && top != '{') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}